using System;
using System.Collections.Specialized;
using System.Threading;
using System.Web;
using System.Web.Security;
using Castle.MonoRail.Framework;
using DecisionesInteligentes.iEvalua.Models;
using DecisionesInteligentes.iEvalua.Web.Services;

namespace DecisionesInteligentes.iEvalua.Web.Filters
{
	public class AuthenticationFilter: Filter{
		
		protected override bool OnBeforeAction(IRailsEngineContext context, Controller controller)
		{
			User user = (User)context.CurrentUser;
			
			if (user == null) {
				
				try
				{
					string cookieContent = context.Request.ReadCookie(FormsAuthentication.FormsCookieName);
					FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookieContent);
					
					int userId = Convert.ToInt32(ticket.Name);
					user = User.Find(userId);
					
					context.CurrentUser = user;
				}catch(Exception ex)
				{
					SendToLoginPage(controller);
					return false;
				}
			}
			
			Thread.CurrentPrincipal = user;
			return true;
		}
		
		private static void SendToLoginPage(Controller controller)
		{
			NameValueCollection dictParams = new NameValueCollection();
			dictParams["returnUrl"] = controller.Context.Request.RawUrl;

			controller.Redirect("login", "index", dictParams);
		}
	}
}

